package com.example.educational.service.impl;

import com.example.educational.controller.utils.Code;
import com.example.educational.controller.utils.SystemException;
import com.example.educational.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class SendMailServiceImpl implements SendMailService {
    //定义一个邮件寄送者
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;     // 发送人
    @Value("${spring.mail.receiver}")
    private String to;     // 接收人


    @Override
    public void sendMail(String subject, String text) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //设置发送人
            mailMessage.setFrom(from + "(智慧管理助手)");
            //设置接收人
            mailMessage.setTo(to);
            //设置邮件主题
            mailMessage.setSubject(subject);
            //设置邮件内容
            mailMessage.setText(text);
            //发送邮件
            javaMailSender.send(mailMessage);
        } catch (MailException e) {
            throw new SystemException(Code.err, "邮件发送失败！！！");
        }
    }
}
